package com.sysd.controller;


import com.alibaba.fastjson.JSONObject;
import com.sysd.bean.entity.User;
import com.sysd.bean.request.LoginRequest;
import com.sysd.bean.response.UserResponse;
import com.sysd.context.UserContext;
import com.sysd.entity.CodeMsg;
import com.sysd.entity.Result;
import com.sysd.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author bsh
 * @since 2025-06-03
 */
@Api("用户操作")
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;

    @ApiOperation("登入")
    @GetMapping("/to-login")
    public Result<UserResponse> toLogin(LoginRequest loginRequest) {
        return Result.success(userService.toLogin(loginRequest));
    }

    @ApiOperation("刷新token")
    @PatchMapping("/flush-token")
    public Result<String> flushToken() {
        if (userService.flushToken()) {
            return Result.success();
        }
        return Result.error(CodeMsg.FLUSH_ERROR);
    }

    @ApiOperation("编辑用户")
    @PutMapping("/")
    public Result<String> updateUser(@RequestBody User user) {
        if (userService.updateUser(user)) {
            return Result.success();
        }
        return Result.error(CodeMsg.UPDATE_ERROR);
    }

    @ApiOperation("注销用户")
    @DeleteMapping("/")
    public Result<String> removeUser() {
        if (userService.removeUser()) {
            return Result.success();
        }
        return Result.error(CodeMsg.REMOVE_ERROR);
    }

    @ApiOperation("关注或者取关，true关注false取关")
    @PatchMapping("/")
    public Result<String> doConcern(Integer userId, boolean isFollow) {
        if (userService.doConcern(userId, isFollow)) {
            return Result.success();
        }
        return Result.error(CodeMsg.DEFAULT, isFollow ? "关注失败!" : "取消关注失败!");
    }

    @ApiOperation("粉丝和关注计数")
    @GetMapping("/fans-f0llow")
    public Result<Object> fansFollow() {
        Integer userId = UserContext.getLoginUser().getUserId();
        Long fansCount = userService.fansCount(userId);
        Long concernCount = userService.concernCount(userId);
        JSONObject jo = new JSONObject();
        jo.put("fansCount", fansCount);
        jo.put("concernCount", concernCount);
        return Result.success(jo);
    }

    @ApiOperation("粉丝列表")
    @GetMapping("fans-list")
    public Result<List<User>> fansList(Integer index, Integer limit) {
        return Result.success(userService.fansList(index, limit));
    }

    @ApiOperation("关注列表")
    @GetMapping("concern-list")
    public Result<List<User>> concernList(Integer index, Integer limit) {
        return Result.success(userService.concernList(index, limit));
    }
}
